//
//  HNCourseEvaluationsVC.m
//  ZYManagementSystem
//
//  Created by 星道 on 17/6/16.
//  Copyright © 2017年 焕宁. All rights reserved.
//

#import "HNCourseEvaluationsVC.h"
#import "ZYCourseAttendanceTowModel.h"
#import "HNCourseEvaluationsTC.h"
#import "HNCourseEvaluationDetailVC.h"
#import "CourseAddStudentVC.h"
#import "PackageListSignView.h"

@interface HNCourseEvaluationsVC ()<UITableViewDelegate,UITableViewDataSource>
{

    IBOutlet UITableView *_TableView;
    IBOutlet UIButton *_AddButton;
}
/**
 所有数据存放
 */
@property (nonatomic, strong) NSMutableArray <ZYCourseAttendanceTowModel *>*dataSource;
/** 已签到的数据存放 */
@property (nonatomic, strong) NSMutableArray <ZYCourseAttendanceTowModel *>*dataSigned;

/**
 是否被全选
 */
@property (nonatomic, assign) BOOL AllSelect;

/**
 全选按钮
 */
@property (strong, nonatomic) IBOutlet UILabel *AllSelect_Btn;
@end

@implementation HNCourseEvaluationsVC

- (void)viewDidLoad {

    [super viewDidLoad];

    [self.AllSelect_Btn addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(ClickAllSelect)]];

    //网络请求数据
    self.RefreshData();

    //预注册
    [_TableView registerNib:[UINib nibWithNibName:[HNCourseEvaluationsTC description] bundle:nil] forCellReuseIdentifier:@"Cell"];
    //占位VIew
    _TableView.tableFooterView = [UIView new];
    //预设高度
    _TableView.rowHeight = UITableViewAutomaticDimension;
    _TableView.estimatedRowHeight = 50;


    _AddButton.hidden = self.IsTaoCanLieBiao;
}




#pragma mark - 网络请求
/**
 网络请求,主页数据获取
 */
- (instancetype (^)())RefreshData {

    return  ^() {

        [HUD showHUD];
        NSDictionary *Params = @{
                                 @"lessonId":self.ID,
                                 @"action"  :self.IsTaoCanLieBiao ? @"lessonRecord" : @"getCourseRecord",
                                 @"oid"         :[AccountTool shareAccountTool].currentAccount.oid
                                 };


        [NetManager Get:LLBaseURL(@"yxhUser.do") Auth:YES Params:Params Success:^(id Obj) {

            if ([Obj[@"code"] isEqualToNumber:@1000])
            {
                [self.dataSource removeAllObjects];
                for (NSDictionary *Dict in Obj[@"t"][@"dataList"])
                {
                    ZYCourseAttendanceTowModel *Model = [[ZYCourseAttendanceTowModel alloc] init_ObjectForValue:Dict];



                    Model.isSign = self.IsTaoCanLieBiao ? Dict[@"isSign"] : Model.isSign;
                    Model.record = self.IsTaoCanLieBiao ? Dict[@"record"] : Model.record;
                    [self.dataSource addObject:Model];
                    //将已签到的数据单独设置为3
                    if ([Model.isSign isEqualToNumber:@2])
                    {
                        Model.isSign = @3;
                        [self.dataSigned addObject:Model];
                    }
                }

                //排序，将所有已签到的放在下面
                [self.dataSource sortUsingComparator:^NSComparisonResult(id obj1, id obj2) {

                    ZYCourseAttendanceTowModel *Model1 = (ZYCourseAttendanceTowModel *)obj1;
                    ZYCourseAttendanceTowModel *Model2 = (ZYCourseAttendanceTowModel *)obj2;

                    NSInteger a = [Model1.isSign integerValue];
                    NSInteger b = [Model2.isSign integerValue];

                    if (a > b)
                    {
                        return NSOrderedDescending;
                    }
                    else if (a < b)
                    {

                        return NSOrderedAscending;
                    }
                    else
                    {
                        return NSOrderedSame;
                    }
                }];


                self.EndRefresh(1);
            }
            else
            {
                [HUD showError:Obj[@"msg"]];
            }
        } Fail:^(NSError *error) {
            [HUD showError:NetErr];
        }];
        return self;
    };
}


/**
 0结束刷新 1通知更新 2告知没有数据了
 */
- (instancetype (^)(NSInteger))EndRefresh {

    return ^(NSInteger Index) {

        dispatch_async(dispatch_get_main_queue(), ^{

            if (Index == 0) {
                [_TableView.mj_footer endRefreshing]; //结束刷新
            } else if (Index == 1) {
                [_TableView reloadData]; //通知更新
            } else if (Index == 2) {
                [_TableView.mj_footer endRefreshingWithNoMoreData]; //告知没有数据了
            } else {

            }

        });
        return self;
    };
}







#pragma mark - 点击事件
/**
 提交签的人
 */
- (IBAction)Suer:(UIButton *)sender {

    self.Sure();
}


/**
 全选切换
 */
- (void)ClickAllSelect {

    self.MgrAllSelect();
}


/**
 增加学生
 */
- (IBAction)AddStudent:(UIButton *)sender
{
    // 处理方法
    [self MgrAddStudent:sender];
}






#pragma mark - 方法
/**
 实现提交方法
 */
- (instancetype (^)())Sure {

    return ^() {

        //临时保存已中状态的对的模型ID
        NSMutableArray *IDArr = [NSMutableArray array];
        NSMutableArray *IDS   = [NSMutableArray array];
        //挑选ID
        [self.dataSource enumerateObjectsUsingBlock:^(ZYCourseAttendanceTowModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {

            ZYCourseAttendanceTowModel *Model = obj;
            //符合就加入豪华晚餐
            [Model.isSign isEqualToNumber:@2]?[IDArr addObject:[Model.user_ID stringValue]]:nil;
            if (self.IsTaoCanLieBiao)
            {
                [Model.isSign isEqualToNumber:@2]?[IDS addObject:Model.orderIds]:nil;
            }
            else
            {
                [Model.isSign isEqualToNumber:@2]?[IDS addObject:[Model.enrollInfoId stringValue]]:nil;

            }
        }];

        // 条件判断
        if (self.dataSource.count > 0 && self.dataSource.count == self.dataSigned.count) {

            [HUD showSuccess:@"所有的学生已签到"];
        } else if (self.dataSource.count > 0 && IDArr.count == 0) {

            [HUD showError:@"请选择学生进行签到"];
        } else if (self.dataSource.count == 0) {

            [HUD showError:@"暂无学生报名该课程"];
        } else {

            //得到最终IDArr后转成字符串
            NSString *IDStr = [IDArr componentsJoinedByString:@","];
            NSString *IDSS = [IDS componentsJoinedByString:@","];
            //提交网络请求
            [PackageListSignView UploadSignInPictureView_ConfigViewWithLessonId:self.ID Uids:IDStr enrollInfoIds:IDSS IsTaoCanLieBiao:self.IsTaoCanLieBiao Complete:^{
                //签到成功，则将数组里的isSign全部设为2
                //将IDStr重新返回数组
                NSArray *IDArr = [IDSS componentsSeparatedByString:@","];

                [IDArr enumerateObjectsUsingBlock:^(NSString * _Nonnull IDStr, NSUInteger idx, BOOL * _Nonnull stop) {

                    [self.dataSource enumerateObjectsUsingBlock:^(ZYCourseAttendanceTowModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                        //匹配条件
                        NSString *obj_IDStr = self.IsTaoCanLieBiao ? obj.orderIds:[obj.enrollInfoId stringValue];
                        if ([obj_IDStr isEqualToString:IDStr]) {
                            
                            obj.isSign = @3;
                            // 将上课次数首位提取出来
                            NSInteger first = [[[obj.record componentsSeparatedByString:@"/"] firstObject] integerValue];
                            NSInteger last = [[[obj.record componentsSeparatedByString:@"/"] lastObject] integerValue];
                            first += 1;
                            obj.record = [NSString stringWithFormat:@"%ld/%ld",first,last];
                        }
                    }];
                }];
                self.EndRefresh(1);
            }];
        }
        return self;
    };
}


/**
 处理选择事件
 */
- (instancetype (^)(ZYCourseAttendanceTowModel *,UIButton *))MgrSelect {

    return  ^(ZYCourseAttendanceTowModel *Model,UIButton *Button) {

        Button.selected = !Button.selected;
        Model.isSign = Button.selected?@2:@1;
        return self;
    };
}

/**
 处理评价事件
 */
- (instancetype (^)(ZYCourseAttendanceTowModel *))MgrEvaluation {

    return  ^(ZYCourseAttendanceTowModel *Model) {

        //评价VC
        HNCourseEvaluationDetailVC *VC = [[HNCourseEvaluationDetailVC alloc] init];
        VC.Account = Model.user_username;
        [self.navigationController pushViewController:VC animated:YES];
        return self;
    };
}


/**
 处理判断全选的
 */
- (instancetype (^)())MgrAllSelect {

    return ^() {

        //遍历赋值选择状态
        [self.dataSource enumerateObjectsUsingBlock:^(ZYCourseAttendanceTowModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            obj.isSign =  [obj.isSign isEqualToNumber:@3] ? @3:self.AllSelect == YES?@2:@1;
        }];
        self.EndRefresh(1);
        //0是选中状态，1是未选中状态
        self.AllSelect = !self.AllSelect;
        return self;
    };
}


/**
 处理增加学生事件
 */
- (void)MgrAddStudent:(UIButton *)Button
{
    //实例化增加学生VC
    CourseAddStudentVC *VC = [[CourseAddStudentVC alloc] init];
    //课程ID值传递
    VC.lessonId = self.ID;
    //推出
    [self.navigationController pushViewController:VC animated:YES];
    // 学生增加之后刷新本界面
    VC.RefreshStudent = ^ () {
        [self.dataSource removeAllObjects];
        [_TableView reloadData];
        //网络请求数据
        self.RefreshData();
    };
}






#pragma mark - TableView代理

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    return self.dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    //取值
    ZYCourseAttendanceTowModel *Model = self.dataSource[indexPath.row];
    HNCourseEvaluationsTC *Cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];
    //Cell赋值
    Cell.Model(Model);
    //单击了选择
    Cell.ClickSelect = ^(UIButton *Button){

        self.MgrSelect(Model,Button);
    };

    //单击了评价
    Cell.ClickEvaluation = ^{

        self.MgrEvaluation(Model);
    };
    return Cell;
}






#pragma mark - 懒加载
- (NSMutableArray<ZYCourseAttendanceTowModel *> *)dataSource {
    if (!_dataSource) {
        
        _dataSource = [NSMutableArray array];
    }
    return _dataSource;
}

- (NSMutableArray<ZYCourseAttendanceTowModel *> *)dataSigned {
    
    if (!_dataSigned)
    {
        _dataSigned = [NSMutableArray array];
    }
    return _dataSigned;
}
@end
